package com.blackrock.das.service;

import javax.annotation.PreDestroy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Host;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Session;

/**
 * The Class CassandraServiceImpl.
 */
@Service
public class CassandraServiceImpl implements CassandraService {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory.getLogger(CassandraServiceImpl.class);

    /** The cluster. */
    private Cluster cluster;

    /** The session. */
    private Session session;

    /**
     * Destroy.
     */
    @PreDestroy
    public void destroy() {
        close();
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.blackrock.das.service.CassandraService#connect(java.lang.String)
     */
    @Override
    public void connect(String node) {

        LOGGER.debug("Establishing connection...");
        cluster = Cluster.builder().addContactPoint(node).build();
        Metadata metadata = cluster.getMetadata();
        LOGGER.debug("Connecting to cluster: {}", metadata.getClusterName());

        for (Host host : metadata.getAllHosts()) {
            LOGGER.debug("Datacenter: {} Host {}; Rack {}", host.getDatacenter(), host.getAddress(), host.getRack());
        }
        session = cluster.connect();
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.blackrock.das.service.CassandraService#close()
     */
    @Override
    public void close() {
        session.shutdown();
        cluster.shutdown();
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.blackrock.das.service.CassandraService#executeQuery(java.lang.String)
     */
    @Override
    public ResultSet executeQuery(String cql) {
        return session.execute(cql);
    }

    /*
     * (non-Javadoc)
     * 
     * @see com.blackrock.das.service.CassandraService#getSession()
     */
    @Override
    public Session getSession() {
        return session;
    }

}
